<?php
/**
 * Created by PhpStorm.
 * User: anyuzhe
 * Date: 2017/3/26
 * Time: 15:06
 */

namespace App\Repositories;

use App\User;
use App\ZL\Library\ErrorCode;
use App\ZL\Library\Openssl;
use InfyOm\Generator\Common\BaseRepository;
use Illuminate\Support\Collection;
use Illuminate\Container\Container as App;

class UsersRepository extends BaseRepository {

    protected $store;

    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    public function model() {
        return 'App\User';
    }

    public function checkHasAndSaveInfo($user)
    {
        $user['unionId'] = isset($user['unionid'])?$user['unionid']:$user['unionId'];
        $user['nickName'] = isset($user['nickname'])?$user['nickname']:$user['nickName'];
        $openId = isset($user['openid'])?$user['openid']:null;
        $user['unionId'] = isset($user['unionid'])?$user['unionid']:$user['unionId'];
        $user['avatarUrl'] = isset($user['headimgurl'])?$user['headimgurl']:$user['avatarUrl'];
        $user['gender'] = isset($user['sex'])?$user['sex']:$user['gender'];
        $hasuser = $this->checkHas(isset($user['unionid'])?$user['unionid']:$user['openId'],isset($user['unionid']));


        $data = [
            'nickname'=>$user['nickName'],
            'avatar_Url'=>$user['avatarUrl'],
            'sex'=>$user['gender'],
            'unionid'=>$user['unionId'],
            'city'=>$user['city'],
            'session_id'=>getSessionId(),
        ];
        if($openId)
            $data['openid'] = $openId;
        if(isset($user['openId']))
            $data['xcx_openid'] = $user['openId'];


        if(!$hasuser){
            $new = $this->create($data);
            return $new->id;
        }else{
            $this->update($data,$hasuser['id']);
            return $hasuser['id'];
        }
    }

    public function getOneByOpenid($openId,$is_xcx=true)
    {
        if($is_xcx)
            $field = 'xcx_openid';
        else
            $field = 'openid';
            return User::where($field,$openId)->first();
    }


    public function saveToken($id,$sessionKey)
    {
        $this->update(['remember_token'=>$sessionKey],$id);
    }

    public function saveTokenAndGetSecret($id,$sessionKey)
    {
        $this->saveToken($id,$sessionKey);
        $data = ['id'=>$id,'remember_token'=>$sessionKey];
        $key = config('app.aes_key');
        $iv = config('app.aes_iv');
        $encrypted = Openssl::encryptByAes($key,$iv,json_encode($data));
        return base64_encode($encrypted);
    }

    public function checkHas($unionid,$is_unionid=true)
    {
        if($is_unionid)
            return $this->findBy('unionid',$unionid);
        else
            return $this->findBy('xcx_openid',$unionid);
    }
}